﻿using UnityEngine.UIElements;
using GraphProcessor;
using UnityEditor;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class SkillEditorToolbarView : ToolbarView
    {
        public SkillEditorToolbarView(BaseGraphView graphView) : base(graphView)
        {
        }

        protected override void AddButtons()
        {
            AddButton("Center", graphView.ResetPositionAndZoom);
            
            bool conditionalProcessorVisible = graphView.GetPinnedElementStatus<SkillEditorProcessorView>() != DropdownMenuAction.Status.Hidden;
            AddToggle("Show SkillEditor Processor", conditionalProcessorVisible, (v) => graphView.ToggleView<SkillEditorProcessorView>());
            
            AddButton("Show In Project", () => EditorGUIUtility.PingObject(graphView.graph), false);
            
            graphView.ClosePinned<PrefabProcessorView>();
        }
    }

    public class SkillEditorProcessorView : PinnedElementView
    {
        SkillEditorProcessor processor;
        BaseGraphView graphView;

        public SkillEditorProcessorView() => title = "SkillEditor Processor";

        protected override void Initialize(BaseGraphView graphView)
        {
            processor = new SkillEditorProcessor(graphView.graph);
            this.graphView = graphView;

            graphView.computeOrderUpdated += processor.UpdateComputeOrder;

            Button runButton = new Button(OnPlay) { name = "ActionButton", text = "导出" };
            Button stepButton = new Button(OnStep) { name = "ActionButton", text = "Step" };
            Button refreshButton = new Button(OnRefresh) { name = "ActionButton", text = "刷新" };
            Button clearButton = new Button(OnClear) { name = "ActionButton", text = "Clear" };

            content.Add(runButton);
            content.Add(stepButton);
            content.Add(refreshButton);
            content.Add(clearButton);
        }

        void OnPlay() => processor.Run();

        void OnStep()
        {
            BaseNodeView view;

            if (processor.currentGraphExecution != null)
            {
                // Unhighlight the last executed node
                view = graphView.nodeViews.Find(v => v.nodeTarget == processor.currentGraphExecution.Current);
                view.UnHighlight();
            }

            processor.Step();

            // Display debug infos, currentGraphExecution is modified in the Step() function above
            if (processor.currentGraphExecution != null)
            {
                view = graphView.nodeViews.Find(v => v.nodeTarget == processor.currentGraphExecution.Current);
                view.Highlight();
            }
        }
        
        void OnRefresh()
        {
            processor.Refresh();
        }

        void OnClear()
        {
            SkillEditorBlackboard.Instance.Clear();
        }
    }
}